package com.wnxy.a_thread;

import java.util.concurrent.*;

/**
 * 创建线程，方式3：Callable 可取消的异步计算，可以获取线程执行结果
 */
public class App3Callable extends Thread{

    public static void main(String[] args) {
        //1、实现计算任务
        Callable<String> callable = ()->{
            int sum = 0;
            for (int i = 1; i <= 1000000; i++) {
                sum += i;
            }
            System.out.println("sum = " + sum);
            return "结果：" + sum;
        };
        //2、创建FutureTask，传入callable
        FutureTask<String> futureTask = new FutureTask<>(callable);
        //3、创建启动线程
        Thread thread = new Thread(futureTask);
        thread.start();

        try {
            //4、获取线程执行的结果(阻塞)
            String result = futureTask.get(1, TimeUnit.SECONDS);
            System.out.println("result = " + result);
            System.out.println(futureTask.isDone());
            System.out.println(futureTask.isCancelled());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
            // 超时中断线程执行
            System.out.println(futureTask.isCancelled());
            futureTask.cancel(true);
        }


        System.out.println(" Finall All= " );
    }
}


















